import logging
import os

from logging import handlers
from conf.settings import DEBUG


# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# logger = logging.getLogger(__name__)


class Logger(object):
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }

    def __init__(self, filename=None, level='info', when='W6', back_count=100,
                 fmt='[pid: %(process)d] [%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)d %(funcName)s] - %(message)s'):

        path = '/var/log/scripts/'
        if not os.path.exists('/var/log/scripts'):
            os.mkdir('/var/log/scripts')
        if not filename:
            path = f"{path}run.log"
        else:
            path = f"{path}{filename}"

        self._logger = logging.getLogger(path)
        format_str = logging.Formatter(fmt)
        self._logger.setLevel(self.level_relations.get(level))

        if not DEBUG:
            th = handlers.TimedRotatingFileHandler(filename=path, when=when, backupCount=back_count, encoding='utf-8')
            th.setFormatter(format_str)
            self._logger.addHandler(th)

        sh = logging.StreamHandler()
        sh.setFormatter(format_str)
        self._logger.addHandler(sh)

    def get_logger(self):
        return self._logger


if __name__ == '__main__':
    logger = Logger().get_logger()
    logger.debug('debug')
    logger.info('info')
    logger.warning('warning')
    logger.error('error')
    logger.critical('critical')
